package cn.iocoder.yudao.module.security.controller.admin.rule;

import cn.hutool.core.io.FileUtil;
import cn.iocoder.yudao.framework.common.util.io.FileUtils;
import io.swagger.v3.oas.annotations.Parameters;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.io.File;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.io.IOException;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.*;

import cn.iocoder.yudao.module.security.controller.admin.rule.vo.*;
import cn.iocoder.yudao.module.security.dal.dataobject.rule.SecurityRuleDO;
import cn.iocoder.yudao.module.security.service.rule.SecurityRuleService;
import org.springframework.web.multipart.MultipartFile;

@Tag(name = "管理后台 - 规则")
@RestController
@RequestMapping("/security/rule")
@Validated
public class SecurityRuleController {

    @Resource
    private SecurityRuleService ruleService;

    @PostMapping("/create")
    @Operation(summary = "创建规则")
    @PreAuthorize("@ss.hasPermission('security:rule:create')")
    public CommonResult<Long> createRule(@Valid @RequestBody SecurityRuleSaveReqVO createReqVO) {
        return success(ruleService.createRule(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新规则")
    @PreAuthorize("@ss.hasPermission('security:rule:update')")
    public CommonResult<Boolean> updateRule(@Valid @RequestBody SecurityRuleSaveReqVO updateReqVO) {
        ruleService.updateRule(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除规则")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('security:rule:delete')")
    public CommonResult<Boolean> deleteRule(@RequestParam("id") Long id) {
        ruleService.deleteRule(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得规则")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('security:rule:query')")
    public CommonResult<SecurityRuleRespVO> getRule(@RequestParam("id") Long id) {
        SecurityRuleDO rule = ruleService.getRule(id);
        return success(BeanUtils.toBean(rule, SecurityRuleRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得规则分页")
    @PreAuthorize("@ss.hasPermission('security:rule:query')")
    public CommonResult<PageResult<SecurityRuleRespVO>> getRulePage(@Valid SecurityRulePageReqVO pageReqVO) {
        PageResult<SecurityRuleDO> pageResult = ruleService.getRulePage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, SecurityRuleRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出规则 Excel")
    @PreAuthorize("@ss.hasPermission('security:rule:export')")
    @OperateLog(type = EXPORT)
    public void exportRuleExcel(@Valid SecurityRulePageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<SecurityRuleDO> list = ruleService.getRulePage(pageReqVO).getList();
        String filename = "all.rules";

        response.setContentType("text/plain");
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
                "attachment; filename=\"" + filename + "\"");
        response.setCharacterEncoding("UTF-8");
        try (PrintWriter writer = response.getWriter()) {
            for (SecurityRuleDO rule : list) {
                writer.println(rule.getContent());
            }
        }
    }

    @PostMapping("/import")
    @Operation(summary = "导出规则")
    @Parameters({
            @Parameter(name = "file", description = "Excel 文件", required = true),
            @Parameter(name = "updateSupport", description = "是否支持更新，默认为 false", example = "true")
    })
    @PreAuthorize("@ss.hasPermission('security:rule:create')")
    public CommonResult<Boolean> importExcel(@RequestParam("file") MultipartFile file,
                                                      @RequestParam(value = "updateSupport", required = false, defaultValue = "false") Boolean updateSupport) throws Exception {
        File tempFile = FileUtil.createTempFile();
        FileUtil.writeFromStream(file.getInputStream(), tempFile);
        List<String> lines = FileUtil.readLines(tempFile, "UTF-8");
        return success(ruleService.importRuleList(lines, updateSupport));
    }

}